package com.decheng.bootmybatisgenerator.service.impl;

import com.decheng.bootmybatisgenerator.entities.User;
import com.decheng.bootmybatisgenerator.mapper.UserMapper;
import com.decheng.bootmybatisgenerator.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.RowBounds;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

/**
 * @Author 孔德成
 * @Slogan 致敬大师，致敬未来的你
 * @date 2021/8/18
 */
@Service
@Slf4j
public class UserServiceImpl implements UserService {

    UserMapper userMapper;

    public UserServiceImpl(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    @Override
    public int add(User user) {
        return userMapper.insertSelective(user);
    }

    @Override
    public int del(Integer id) {
        return userMapper.deleteByPrimaryKey(id);
    }

    @Override
    public int update(User user) {
        return userMapper.updateByPrimaryKey(user);
    }

    @Override
    public User getById(Integer id) {
        return userMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<User> getByCondition(User user) {
        return userMapper.select(user);
    }

    @Override
    public List<User> getSplitPage(User user) {
        // 根据 user 属性值查询所有记录
        System.out.println("*****total records: " + userMapper.selectCount(user));
        // 返回分页的结果，只显示前3条记录
        return userMapper.selectByRowBounds(user, new RowBounds(0, 3));
    }

    @Override
    public List<User> getSplitPageExample(User user) {
        // 通用的查询对象
        Example example = new Example(User.class);
        // 创建查询条件
        Example.Criteria criteria = example.createCriteria();
        // 对 username 属性进行模糊查询
        criteria.andLike("username", user.getUsername() + "%");
        return userMapper.selectByExampleAndRowBounds(example, new RowBounds(0, 7));

    }
}
